import re
from functools import lru_cache
from PIL import Image

def image_to_tilemap(path, tilesize = 4, autocrop = True):
	image = Image.open(path)
	if autocrop:
		image = image.crop(image.getbbox())

	w, h = image.size
	pixel = image.load()
	assert(w % tilesize == 0)
	assert(h % tilesize == 0)

	result = []
	for y in range(0, w, 4):
		temp = []
		for x in range(0, h, 4):
			temp.append(pixel[x, y])

		result.append(temp)

	return result

def hex_to_tuple(s):
	s = s.upper()
	if s[0] == "#":
		s = s[1:]
	if len(s) == 3:
		return tuple(int(i, 16)*16 for i in s)
	elif len(s) == 6:
		return tuple(int(i, 16) for i in [s[0:2],s[2:4],s[4:6]])
	else:
		raise RuntimeError("Cannot convert: " + s)

def dist(c1, c2):
	return sum(abs(c1[i]-c2[i]) for i in range(3))

def get_nearest_color(colorset, color = None):
	@lru_cache
	def fn(color):
		if len(color) == 4 and color[-1] == 0:
			return (0,0,0,0)
		array = []
		for c in colorset:
			array.append([dist(c, color), c])
		array.sort()
		if array[0][0] > 64:
			raise RuntimeError("Reach max tolerance: " + str(array[0][0]))
		return array[0][1]

	if color == None:
		return fn
	else:
		return fn(color)


if __name__ == '__main__':
	print(dist([0,0,0], [255,0,255]))
	print(hex_to_tuple("#0F0"))
	print(hex_to_tuple("00FFFF"))
	m = image_to_tilemap("template.PNG")
	print(len(m), len(m[0]))